#include<head.h>

int main(int argc, char const *argv[])
{
    //1、创建套接字
    int soket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(soket_fd == -1)
    {
        perror("socket");
        exit(1);
    }
    //2、绑定
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8888);
    server_addr.sin_addr.s_addr = inet_addr("192.168.10.248");
    socklen_t len_1 = sizeof(server_addr);
    if(bind(soket_fd, (struct sockaddr*)&server_addr, len_1) == -1)
    {
        perror("bind");
        exit(1);
    }
    //3、监听
    if(listen(soket_fd, 10) == -1)
    {
        perror("listen");
        exit(1);
    }
    //4、接受连接 阻塞等待客户端连接
    printf("等待客户端连接\n");
    struct sockaddr_in client_addr;
    socklen_t len = sizeof(client_addr);
    int new_socket_fd = accept(soket_fd, (struct sockaddr*)&client_addr, &len);
    if(new_socket_fd == -1)
    {
        perror("accept");
        exit(1);
    }
    printf("客户端连接成功\n");
    //5、通信
    char buf[1024];
    while(1)
    {
        memset(buf, 0, sizeof(buf));
        int ret = read(new_socket_fd, buf, sizeof(buf));
        if(ret == -1)
        {
            perror("read");
            exit(1);
        }
        else if(ret == 0)
        {
            printf("客户端断开连接\n");
            break;
        }
        printf("客户端发送信息：%s\n", buf);
    }
    //6、关闭套接字
    close(new_socket_fd);
    close(soket_fd);
    return 0;
}
